/**
 * 菜单管理模块
 * 负责创建和管理Dock菜单、系统托盘菜单等
 * 使用函数式编程风格
 * @author LYC
 * @date 2025-09-13
 */

import { Menu, Tray, app } from 'electron'
import { AppExitManager } from '../app/appExit'

/**
 * 菜单项配置接口
 */
export interface MenuItemConfig {
  label: string
  action: () => void
  type?: 'normal' | 'separator'
}

/**
 * 托盘配置接口
 */
export interface TrayConfig {
  icon: string
  tooltip: string
  menuItems: MenuItemConfig[]
  onDoubleClick?: () => void
}

/**
 * 创建菜单项的纯函数
 */
const createMenuItem = (config: MenuItemConfig): Electron.MenuItemConstructorOptions => {
  if (config.type === 'separator') {
    return { type: 'separator' }
  }

  return {
    label: config.label,
    click: config.action
  }
}

/**
 * 创建菜单模板的纯函数
 */
const createMenuTemplate = (items: MenuItemConfig[]): Electron.MenuItemConstructorOptions[] => {
  return items.map(createMenuItem)
}

/**
 * 创建标准应用菜单项的工厂函数
 */
export const createStandardMenuItems = (
  exitManager: AppExitManager
): {
  showWindow: () => MenuItemConfig
  hideWindow: () => MenuItemConfig
  separator: () => MenuItemConfig
  quitApp: (source: string) => MenuItemConfig
} => ({
  showWindow: (): MenuItemConfig => ({
    label: '显示窗口',
    action: () => exitManager.showAvailableWindow()
  }),

  hideWindow: (): MenuItemConfig => ({
    label: '隐藏窗口',
    action: () => exitManager.hideAllWindows()
  }),

  separator: (): MenuItemConfig => ({
    label: '',
    type: 'separator' as const,
    action: () => {}
  }),

  quitApp: (source: string): MenuItemConfig => ({
    label: '退出应用',
    action: () => {
      console.log(`${source}: User clicked quit application`)
      exitManager.quitApplication()
    }
  })
})

/**
 * 创建Dock菜单的纯函数
 */
export const createDockMenu = (exitManager: AppExitManager) => (): void => {
  if (process.platform !== 'darwin') return

  const menuFactory = createStandardMenuItems(exitManager)
  const menuItems = [
    menuFactory.showWindow(),
    menuFactory.hideWindow(),
    menuFactory.separator(),
    menuFactory.quitApp('Dock menu')
  ]

  const dockMenu = Menu.buildFromTemplate(createMenuTemplate(menuItems))
  app.dock?.setMenu(dockMenu)
  console.log('Dock menu created successfully')
}

/**
 * 创建系统托盘的高阶函数
 */
export const createSystemTray = (config: TrayConfig, exitManager: AppExitManager) => (): Tray => {
  const tray = new Tray(config.icon)

  // 创建菜单
  const contextMenu = Menu.buildFromTemplate(createMenuTemplate(config.menuItems))
  tray.setContextMenu(contextMenu)
  tray.setToolTip(config.tooltip)

  // 设置双击事件
  if (config.onDoubleClick) {
    tray.on('double-click', config.onDoubleClick)
  }

  // 更新退出管理器的托盘引用
  exitManager.setTray(tray)

  console.log('System tray created successfully')
  return tray
}

/**
 * 创建标准托盘配置的工厂函数
 */
export const createStandardTrayConfig = (icon: string, exitManager: AppExitManager): TrayConfig => {
  const menuFactory = createStandardMenuItems(exitManager)

  return {
    icon,
    tooltip: 'XLChat',
    menuItems: [
      menuFactory.showWindow(),
      menuFactory.hideWindow(),
      menuFactory.separator(),
      menuFactory.quitApp('System tray')
    ],
    onDoubleClick: () => exitManager.showAvailableWindow()
  }
}

/**
 * 菜单管理器类（函数式风格）
 */
export class MenuManager {
  private static instance: MenuManager
  private exitManager: AppExitManager
  private tray: Tray | null = null

  private constructor(exitManager: AppExitManager) {
    this.exitManager = exitManager
  }

  public static getInstance(exitManager: AppExitManager): MenuManager {
    if (!MenuManager.instance) {
      MenuManager.instance = new MenuManager(exitManager)
    }
    return MenuManager.instance
  }

  /**
   * 初始化所有菜单
   */
  public initializeMenus = (icon: string): MenuManager => {
    // 使用函数组合的方式初始化菜单
    const initDockMenu = createDockMenu(this.exitManager)
    const initSystemTray = this.createSystemTrayInitializer(icon)

    // 执行初始化
    initDockMenu()
    this.tray = initSystemTray()

    return this
  }

  /**
   * 创建系统托盘初始化器的私有方法
   */
  private createSystemTrayInitializer = (icon: string) => {
    const trayConfig = createStandardTrayConfig(icon, this.exitManager)
    return createSystemTray(trayConfig, this.exitManager)
  }

  /**
   * 获取托盘实例
   */
  public getTray = (): Tray | null => this.tray

  /**
   * 清理资源
   */
  public cleanup = (): void => {
    if (this.tray) {
      this.tray.destroy()
      this.tray = null
    }
    console.log('Menu Manager cleanup completed')
  }
}

/**
 * 获取菜单管理器实例的工厂函数
 */
export const getMenuManager = (exitManager: AppExitManager): MenuManager => {
  return MenuManager.getInstance(exitManager)
}

/**
 * 创建菜单初始化器的高阶函数
 */
export const createMenuInitializer = (exitManager: AppExitManager, icon: string) => {
  const menuManager = getMenuManager(exitManager)

  return () => {
    menuManager.initializeMenus(icon)
    return menuManager.getTray()
  }
}
